<template>
  <Transition name="dialog">
    <div class="dialog" v-show="visible">
      <!-- 遮罩层 -->
      <div class="dialog-mask" @click="close"></div>
      <!-- 内容区 -->
      <div class="dialog-wrap" :style="{ width }">
        <!-- 头部 -->
        <div class="dialog-header">
          <div class="dialog-title">{{ title }}</div>
          <div class="dialog-close" @click="close">
            <sicon type="3.1关闭" />
          </div>
        </div>
        <!-- 内容区 -->
        <div class="dialog-content">
          <!-- 显示默认插槽的内容 -->
          <slot />
        </div>
        <!-- 底部 -->
        <div class="dialog-footer">
          <!-- 显示具名插槽的内容 -->
          <slot name="footer" />
        </div>
      </div>
    </div>
  </Transition>
</template>

<script lang="ts">
export default {
  name: "SDialog",
};
</script>
<script lang="ts" setup>
import sicon from "@/components/sicon/sicon.vue";
import {
  defineProps,
  defineEmits,
  watch,
  onBeforeUnmount,
  h,
  Transition,
} from "vue";
h(Transition, {
  /* props */
  name: "dialog",
});
const props = defineProps({
  // 标题
  title: {
    type: String,
    default: "",
  },
  // 弹框显示隐藏
  visible: {
    type: Boolean,
    default: false,
  },
  // 弹框宽度
  width: {
    type: String,
    default: "50%",
  },
});
const emit = defineEmits(["isShow"]);
const close = () => {
  emit("isShow");
};
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      // 禁用滚动条
      document.documentElement.style.overflow = "hidden";
      return;
    }
    // 不禁用
    document.documentElement.style.overflow = "auto";
  },
  {
    immediate: true,
  }
);
onBeforeUnmount(() => {
  document.documentElement.style.overflow = "auto";
});
</script>

<style lang="less" scoped>
.dialog {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 99;
  display: flex;
  justify-content: center;
  align-items: center;
}

.dialog-mask {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: -1;
}

.dialog-wrap {
  background-color: #fff;
  padding: 20px;
  border-radius: 5px;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
}

.dialog-title {
  font-size: 18px;
  font-weight: bold;
}

.dialog-close {
  font-size: 14px;
  color: #999;
  cursor: pointer;
  &:hover {
    color: red;
  }
}

.dialog-content {
  padding: 20px 0;
  font-size: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
